package vn.com.vega.music.clientserver;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.com.vega.music.objects.Ringtone;

public class JsonRingtone extends JsonBase {

	public ArrayList<Ringtone> ringtunes;

	protected JsonRingtone() {
	}

	public static JsonRingtone loadRingtuneListBySong(String songName,
			int offset) {
		String url = ClientServer.getInstance().getUrlListRingtuneBySong(
				songName, offset);
		return loadRingtuneList(url);
	}

	protected static JsonRingtone loadRingtuneList(String url) {
		JsonRingtone result = new JsonRingtone();
		JSONObject json = result.requestAndParseBasicJson(url);
		if (result.isSuccess()) {
			result.parseRingtune(json);
		}
		return result;
	}

	public static JsonRingtone registerRingtune(String ringCode, int phoneNumber) {
		String registerUrl = ClientServer.getInstance()
				.getUrlRegisterForPhoneNumber(ringCode, phoneNumber);
		JsonRingtone result = new JsonRingtone();
		result.requestAndParseBasicJson(registerUrl);
		return result;
	}

	/**
	 * parse ringtune json from server return: JsonRingtune object
	 */
	protected void parseRingtune(JSONObject json) {
		try {
			// channel category
			ArrayList<Ringtone> listRing = new ArrayList<Ringtone>();
			JSONArray aData = json.getJSONArray("data");
			for (int i = 0; i < aData.length(); i++) {
				JSONObject o = aData.getJSONObject(i);
				Ringtone ring = new Ringtone();

				try {
					ring.id = o.getInt("id");
					ring.code = o.getString("code");
					ring.title = o.getString("title");
					ring.streamingUrl = o.getString("url_streaming");
					ring.artist = o.getString("artist_name");
					ring.price = o.getString("price");
					ring.registeredCount = o.getInt("downloaded_count");
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

				listRing.add(ring);
			}
			this.ringtunes = listRing;
		} catch (Exception ex) {
			setParsingError();
		}
	}
}
